
package org.apache.solr.response.transform;

import java.io.IOException;
import org.apache.lucene.search.Explanation;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.util.SolrPluginUtils;

/**
 * @since solr 4.0
 */
public class ExplainAugmenterFactory extends TransformerFactory {

    public static enum Style {
        nl,
        text,
        html
    };
    protected Style defaultStyle = null;

    @Override
    public void init(NamedList args) {
        super.init(args);

        if(defaultUserArgs != null) {
            defaultStyle = getStyle(defaultUserArgs);
        }
        else {
            defaultStyle = Style.nl;
        }
    }

    public static Style getStyle(String str) {

        try {
            return Style.valueOf(str);
        }
        catch(Exception ex) {
            throw new SolrException(ErrorCode.BAD_REQUEST, "Unknown Explain Style: " + str);
        }
    }

    @Override
    public DocTransformer create(String field, SolrParams params, SolrQueryRequest req) {

        String s = params.get("style");
        Style style = (s == null) ? defaultStyle : getStyle(s);
        return new ExplainAugmenter(field, style);
    }

    static class ExplainAugmenter extends TransformerWithContext {

        final String name;
        final Style style;

        public ExplainAugmenter(String display, Style style) {
            this.name = display;
            this.style = style;
        }

        @Override
        public String getName() {
            return name;
        }

        @Override
        public void transform(SolrDocument doc, int docid) {

            if(context != null && context.query != null) {
                try {
                    Explanation exp = context.searcher.explain(context.query, docid);
                    if(style == Style.nl) {
                        doc.setField(name, SolrPluginUtils.explanationToNamedList(exp));
                    }
                    else if(style == Style.html) {
                        doc.setField(name, exp.toHtml());
                    }
                    else {
                        doc.setField(name, exp.toString());
                    }
                }
                catch(IOException e) { }
            }
        }
    }
}
